package com.sujeet.learning.core_analysis;

/* jstack relevant section:

Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x09b463e8 (object 0xa9aede38, a com.sujeet.learning.core_analysis.Deadlock$Friend),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x09b47c20 (object 0xa9aede28, a com.sujeet.learning.core_analysis.Deadlock$Friend),
  which is held by "Thread-1"

Java stack information for the threads listed above:
===================================================
"Thread-1":
	at com.sujeet.learning.core_analysis.Deadlock$Friend.bowBack(Deadlock.java:19)
	- waiting to lock <0xa9aede38> (a com.sujeet.learning.core_analysis.Deadlock$Friend)
	at com.sujeet.learning.core_analysis.Deadlock$Friend.bow(Deadlock.java:16)
	- locked <0xa9aede28> (a com.sujeet.learning.core_analysis.Deadlock$Friend)
	at com.sujeet.learning.core_analysis.Deadlock$2.run(Deadlock.java:34)
	at java.lang.Thread.run(Thread.java:662)
"Thread-0":
	at com.sujeet.learning.core_analysis.Deadlock$Friend.bowBack(Deadlock.java:19)
	- waiting to lock <0xa9aede28> (a com.sujeet.learning.core_analysis.Deadlock$Friend)
	at com.sujeet.learning.core_analysis.Deadlock$Friend.bow(Deadlock.java:16)
	- locked <0xa9aede38> (a com.sujeet.learning.core_analysis.Deadlock$Friend)
	at com.sujeet.learning.core_analysis.Deadlock$1.run(Deadlock.java:31)
	at java.lang.Thread.run(Thread.java:662)

Found 1 deadlock.

*/
public class Deadlock {
    static class Friend {
        private final String name;
        public Friend(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        public synchronized void bow(Friend bower) {
            System.out.format("%s: %s"
                + "  has bowed to me!%n", 
                this.name, bower.getName());
            bower.bowBack(this);
        }
        public synchronized void bowBack(Friend bower) {
            System.out.format("%s: %s"
                + " has bowed back to me!%n",
                this.name, bower.getName());
        }
    }

    public static void main(String[] args) {
        final Friend alphonse =
            new Friend("Alphonse");
        final Friend gaston =
            new Friend("Gaston");
        new Thread(new Runnable() {
            public void run() { alphonse.bow(gaston); }
        }).start();
        new Thread(new Runnable() {
            public void run() { gaston.bow(alphonse); }
        }).start();
    }
}
